<?php
require_once __DIR__ . '/config.php';
require_once __DIR__ . '/login_check.php';
require_once __DIR__ . '/manage_index.php';
session_start();
check_admin_session();

class MediaManager {
    private $pdo;
    
    public function __construct($pdo) {
        $this->pdo = $pdo;
        $this->ensureTablesExist();
    }

    private function ensureTablesExist() {
        try {
            $this->pdo->query("SELECT 1 FROM media_config LIMIT 1");
        } catch (PDOException $e) {
            $this->pdo->exec("
                CREATE TABLE IF NOT EXISTS media_config (
                    id INT PRIMARY KEY AUTO_INCREMENT,
                    position_top VARCHAR(20) DEFAULT '1vw',
                    position_left VARCHAR(20) DEFAULT '1vw',
                    width VARCHAR(20) DEFAULT '20vw',
                    height VARCHAR(20) DEFAULT '18vh',
                    object_fit ENUM('cover', 'contain', 'fill') DEFAULT 'cover'
                )
            ");
        }
    }

    public function getActiveMedia($max = PHP_INT_MAX) {
        $stmt = $this->pdo->prepare("
            SELECT * FROM media_resources 
            WHERE is_active = 1 
            ORDER BY display_order ASC, created_at DESC 
            LIMIT :max
        ");
        $stmt->bindParam(':max', $max, PDO::PARAM_INT);
        $stmt->execute();
        return $stmt->fetchAll(PDO::FETCH_ASSOC);
    }

    public function uploadMedia($title, $file, $display_order) {
        $upload_dir = 'uploads/';
        $ext = pathinfo($file['name'], PATHINFO_EXTENSION);
        $type = $this->getMediaType($ext);
        
        if (!$type) return ['error' => '不支持的文件类型'];
        
        if (!is_dir($upload_dir)) mkdir($upload_dir, 0755, true);
        
        $filename = uniqid() . '.' . $ext;
        $destination = $upload_dir . $filename;
        
        if (!move_uploaded_file($file['tmp_name'], $destination)) {
            return ['error' => '文件上传失败'];
        }
        
        $stmt = $this->pdo->prepare("
            INSERT INTO media_resources (title, type, url, display_order, is_active)
            VALUES (:title, :type, :url, :display_order, 1)
        ");
        
        $params = [
            ':title' => $title,
            ':type' => $type,
            ':url' => $destination,
            ':display_order' => $display_order
        ];
        
        if ($stmt->execute($params)) {
            return ['success' => '上传成功'];
        } else {
            return ['error' => '数据库错误'];
        }
    }

    private function getMediaType($ext) {
        $image_exts = ['jpg', 'jpeg', 'png', 'gif'];
        $video_exts = ['mp4', 'webm', 'ogg'];
        
        if (in_array(strtolower($ext), $image_exts)) return 'image';
        if (in_array(strtolower($ext), $video_exts)) return 'video';
        return null;
    }

    public function deleteMedia($id) {
        $stmt = $this->pdo->prepare("SELECT url FROM media_resources WHERE id = :id");
        $stmt->execute([':id' => $id]);
        $media = $stmt->fetch(PDO::FETCH_ASSOC);
        
        if ($media && file_exists($media['url'])) {
            unlink($media['url']);
        }
        
        $stmt = $this->pdo->prepare("DELETE FROM media_resources WHERE id = :id");
        return $stmt->execute([':id' => $id]);
    }

    public function editMedia($id, $title, $display_order, $start_time = null, $end_time = null) {
        $stmt = $this->pdo->prepare("
            UPDATE media_resources 
            SET title = :title, 
                display_order = :display_order,
                start_time = :start_time,
                end_time = :end_time
            WHERE id = :id
        ");
        return $stmt->execute([
            ':title' => $title,
            ':display_order' => $display_order,
            ':id' => $id,
            ':start_time' => $start_time,
            ':end_time' => $end_time
        ]);
    }

    public function getCarouselConfig() {
        $stmt = $this->pdo->query("SELECT * FROM media_config LIMIT 1");
        return $stmt->fetch(PDO::FETCH_ASSOC) ?: [];
    }

    public function updateCarouselConfig($data) {
        $config = $this->getCarouselConfig();
        
        if (empty($config)) {
            $stmt = $this->pdo->prepare("
                INSERT INTO media_config (position_top, position_left, width, height, object_fit)
                VALUES (:top, :left, :width, :height, :object_fit)
            ");
        } else {
            $stmt = $this->pdo->prepare("
                UPDATE media_config 
                SET position_top = :top, 
                    position_left = :left, 
                    width = :width, 
                    height = :height,
                    object_fit = :object_fit
                WHERE id = :id
            ");
            $data['id'] = $config['id'];
        }
        
        return $stmt->execute($data);
    }
}

$mediaManager = new MediaManager($pdo);

// 处理表单提交
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if (isset($_POST['action'])) {
        switch ($_POST['action']) {
            case 'delete':
                $id = intval($_POST['id']);
                if ($mediaManager->deleteMedia($id)) {
                    $_SESSION['message'] = '删除成功';
                } else {
                    $_SESSION['message'] = '删除失败';
                }
                break;
                
            case 'edit':
    $id = intval($_POST['id']);
    $title = $_POST['title'];
    $display_order = intval($_POST['display_order']);
    
    // 关键修改：将空字符串转换为 NULL（适配数据库 datetime 类型的 NULL 允许）
    $start_time = isset($_POST['start_time']) && trim($_POST['start_time']) !== '' 
        ? $_POST['start_time'] 
        : null;
    $end_time = isset($_POST['end_time']) && trim($_POST['end_time']) !== '' 
        ? $_POST['end_time'] 
        : null;
    
    if ($mediaManager->editMedia($id, $title, $display_order, $start_time, $end_time)) {
        $_SESSION['message'] = '修改成功';
    } else {
        $_SESSION['message'] = '修改失败';
    }
    break;
                
            case 'update_config':
                $top = $_POST['position_top'];
                $left = $_POST['position_left'];
                $width = $_POST['width'];
                $height = $_POST['height'];
                $objectFit = $_POST['object_fit'];
                
                if ($mediaManager->updateCarouselConfig([
                    'top' => $top,
                    'left' => $left,
                    'width' => $width,
                    'height' => $height,
                    'object_fit' => $objectFit
                ])) {
                    $_SESSION['message'] = '配置更新成功';
                } else {
                    $_SESSION['message'] = '配置更新失败';
                }
                break;
                
            case 'add':
                if (isset($_FILES['media_file']) || isset($_POST['video_url'])) {
                    if (isset($_FILES['media_file']) && $_FILES['media_file']['error'] === 0) {
                        $result = $mediaManager->uploadMedia(
                            $_POST['title'],
                            $_FILES['media_file'],
                            intval($_POST['display_order'])
                        );
                    } elseif (isset($_POST['video_url'])) {
                        $upload_dir = 'uploads/';
                        if (!is_dir($upload_dir)) mkdir($upload_dir, 0755, true);
                        $url = $_POST['video_url'];
                        $ext = pathinfo(parse_url($url, PHP_URL_PATH), PATHINFO_EXTENSION);
                        $type = $mediaManager->getMediaType($ext);
                        if (!$type) {
                            $result = ['error' => '不支持的文件类型'];
                        } else {
                            $filename = uniqid() . '.' . $ext;
                            $destination = $upload_dir . $filename;
                            if (copy($url, $destination)) {
                                $stmt = $pdo->prepare("
                                    INSERT INTO media_resources (title, type, url, display_order, is_active)
                                    VALUES (:title, :type, :url, :display_order, 1)
                                ");
                                $params = [
                                    ':title' => $_POST['title'],
                                    ':type' => $type,
                                    ':url' => $destination,
                                    ':display_order' => intval($_POST['display_order'])
                                ];
                                if ($stmt->execute($params)) {
                                    $result = ['success' => '上传成功'];
                                } else {
                                    $result = ['error' => '数据库错误'];
                                }
                            } else {
                                $result = ['error' => '文件下载失败'];
                            }
                        }
                    }
                    $_SESSION['message'] = $result['success'] ?? $result['error'];
                }
                break;
        }
    }
    
    header("Location: media.php");
    exit;
}

$all_media = $mediaManager->getActiveMedia(PHP_INT_MAX);
$config = $mediaManager->getCarouselConfig();
?>

<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <title>新闻管理</title>
    <!-- 新增：引入图标库（侧边栏需要） -->
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@mdi/font@7.4.47/css/materialdesignicons.min.css">
    <style>
        /* 新增：主内容区域样式（与侧边栏配合） */
        body {
            font-family: "Microsoft YaHei", Arial, sans-serif;
            margin: 0;
            padding: 0;
            display: flex;
            min-height: 100vh;
            background: #f5f7fa;
        }
        
        .main-content {
            margin-left: 240px; /* 与侧边栏宽度匹配 */
            width: 100%;
            padding: 48px 32px 32px 32px;
            box-sizing: border-box;
        }
        
        .manage-panel {
            max-width: 1000px;
            margin: 0 auto;
            background: #fff;
            border-radius: 16px;
            box-shadow: 0 4px 18px rgba(41, 128, 255, 0.08);
            padding: 32px;
        }

        /* 保留原有的媒体管理样式 */
        table {border-collapse: collapse; width: 100%; margin-bottom: 20px;}
        th, td {border: 1px solid #ddd; padding: 8px; text-align: left;}
        tr:nth-child(even) {background-color: #f2f2f2;}
        .actions {display: flex; gap: 8px;}
        .btn {padding: 6px 12px; background-color: #4CAF50; color: white; border: none; border-radius: 4px; cursor: pointer;}
        .btn.del {background-color: #f44336;}
        .btn.edit {background-color: #2196F3;}
        .message {padding: 10px; margin: 10px 0; border-radius: 4px;}
        .success {background-color: #d4edda; color: #155724;}
        .error {background-color: #f8d7da; color: #721c24;}
        .config-form {background-color: #f0f0f0; padding: 15px; margin-bottom: 20px; border-radius: 8px;}
        .config-form label {margin-right: 15px;}
        .config-form input, .config-form select {padding: 6px; margin-right: 10px; border: 1px solid #ddd; border-radius: 4px;}
        .media-preview {display: flex; gap: 10px; margin-top: 20px; flex-wrap: wrap;}
        .media-preview-item {width: 150px; height: 100px; border: 1px solid #eee; border-radius: 4px; overflow: hidden; position: relative;}
        .media-preview-item img, .media-preview-item video {width: 100%; height: 100%; object-fit: cover;}
        .preview-remove {position: absolute; top: -5px; right: -5px; background: #ff4444; color: white; width: 20px; height: 20px; border-radius: 50%; display: flex; justify-content: center; align-items: center; cursor: pointer; font-size: 12px;}
        .upload-area {border: 2px dashed #ccc; padding: 20px; text-align: center; margin-bottom: 20px; cursor: pointer; transition: all 0.3s;}
        .upload-area:hover {border-color: #4CAF50; background-color: #f9f9f9;}
        .media-list {margin-top: 30px;}
        .media-list th {background-color: #f0f0f0;}
        .media-thumb {width: 80px; height: 50px; object-fit: cover; border-radius: 3px;}

        /* 新增：响应式适配（与侧边栏同步） */
        @media (max-width: 900px) {
            .main-content {
                margin-left: 56px;
                padding: 24px 12px;
            }
            .manage-panel {
                padding: 16px;
            }
        }
    </style>
</head>
<body>
    <!-- 新增：渲染侧边栏 -->
    <?php render_sidebar(); ?>
    
    <!-- 新增：主内容容器 -->
    <div class="main-content">
        <div class="manage-panel">
            <h2><span class="mdi mdi-video"></span>媒体播放</h2>
            <?php if (isset($_SESSION['message'])): ?>
                <div class="message <?php echo strpos($_SESSION['message'], '成功')!== false ? 'success' : 'error'; ?>">
                    <?php echo htmlspecialchars($_SESSION['message']); ?>
                </div>
                <?php unset($_SESSION['message']); ?>
            <?php endif; ?>
    
    <!-- 上传区域 -->
    <div class="upload-area" id="upload-area">
        <h3>添加媒体资源</h3>
        <p>点击或拖拽文件到此处上传，也可输入视频 URL</p>
        <form method="post" enctype="multipart/form-data" id="upload-form">
            <input type="hidden" name="action" value="add">
            <div style="margin-bottom: 10px;">
                <label>标题: <input type="text" name="title" required></label>
            </div>
            <div style="margin-bottom: 10px;">
                <label>文件: <input type="file" name="media_file" id="file-input"></label>
                <label>视频 URL: <input type="text" name="video_url"></label>
            </div>
            <div style="margin-bottom: 10px;">
                <label>排序: <input type="number" name="display_order" value="0"></label>
            </div>
            <button class="btn" type="submit">上传</button>
        </form>
        
        <!-- 预览区域 -->
        <div class="media-preview" id="preview-container"></div>
    </div>
    
    <!-- 媒体列表 -->
    <div class="media-list">
        <h3>已上传媒体</h3>
        <table>
            <tr>
                <th>缩略图</th>
                <th>标题</th>
                <th>类型</th>
                <th>排序</th>
                <th>开始时间</th>
                <th>结束时间</th>
                <th>操作</th>
            </tr>
            <?php foreach ($all_media as $media): ?>
    <tr>
        <td>
            <?php if ($media['type'] === 'image'): ?>
                <img src="<?php echo htmlspecialchars($media['url']); ?>" alt="<?php echo htmlspecialchars($media['title']); ?>" class="media-thumb">
            <?php else: ?>
                <video width="80" height="50" controls muted>
                    <source src="<?php echo htmlspecialchars($media['url']); ?>" type="video/<?php echo pathinfo($media['url'], PATHINFO_EXTENSION); ?>">
                    您的浏览器不支持视频播放。
                </video>
            <?php endif; ?>
        </td>
        <td><?php echo htmlspecialchars($media['title']); ?></td>
        <td><?php echo $media['type']; ?></td>
        <td><?php echo $media['display_order']; ?></td>
        <td>
            <input type="datetime-local" name="start_time" value="<?php echo htmlspecialchars($media['start_time']); ?>">
        </td>
        <td>
            <input type="datetime-local" name="end_time" value="<?php echo htmlspecialchars($media['end_time']); ?>">
        </td>
        <td class="actions">
            <!-- 优化后的操作栏：添加提示字并保持样式一致 -->
            <form method="post" style="display: flex; flex-wrap: wrap; gap: 8px; align-items: center;">
                <input type="hidden" name="action" value="edit">
                <input type="hidden" name="id" value="<?php echo $media['id']; ?>">
                
                <!-- 标题输入框 + 提示 -->
                <div style="display: flex; flex-direction: column; gap: 4px;">
                    <label style="font-size: 0.85em; color: #666;">标题</label>
                    <input type="text" name="title" value="<?php echo htmlspecialchars($media['title']); ?>" required 
                           style="width: 120px; padding: 6px; border: 1px solid #ddd; border-radius: 4px;">
                </div>
                
                <!-- 排序输入框 + 提示 -->
                <div style="display: flex; flex-direction: column; gap: 4px;">
                    <label style="font-size: 0.85em; color: #666;">排序<br>
                    </label>
                    <input type="number" name="display_order" value="<?php echo $media['display_order']; ?>" required 
                           style="width: 80px; padding: 6px; border: 1px solid #ddd; border-radius: 4px;">
                </div>
                
                <!-- 开始时间输入框 + 提示 -->
                <div style="display: flex; flex-direction: column; gap: 4px;">
                    <label style="font-size: 0.85em; color: #666;">生效开始时间</label>
                    <input type="datetime-local" name="start_time" value="<?php echo htmlspecialchars($media['start_time']); ?>" 
                           style="width: 160px; padding: 6px; border: 1px solid #ddd; border-radius: 4px;">
                </div>
                
                <!-- 结束时间输入框 + 提示 -->
                <div style="display: flex; flex-direction: column; gap: 4px;">
                    <label style="font-size: 0.85em; color: #666;">生效结束时间</label>
                    <input type="datetime-local" name="end_time" value="<?php echo htmlspecialchars($media['end_time']); ?>" 
                           style="width: 160px; padding: 6px; border: 1px solid #ddd; border-radius: 4px;">
                </div>
                
                <!-- 编辑按钮 -->
                <button class="btn edit" type="submit" style="align-self: flex-end; margin-top: auto;">
                    <span class="mdi mdi-pencil"></span> 编辑
                </button>
            </form>
            
            <!-- 删除按钮 -->
            <form method="post" onsubmit="return confirm('确定删除此媒体资源？');" style="margin-top: 8px;">
                <input type="hidden" name="action" value="delete">
                <input type="hidden" name="id" value="<?php echo $media['id']; ?>">
                <button class="btn del" type="submit">
                    <span class="mdi mdi-trash-can"></span> 删除
                </button>
            </form>
        </td>
    </tr>
<?php endforeach; ?>
        </table>
    </div>
    
    
    
    <script>
        // 文件上传预览
        document.addEventListener('DOMContentLoaded', function() {
            const fileInput = document.getElementById('file-input');
            const previewContainer = document.getElementById('preview-container');
            
            fileInput.addEventListener('change', function(e) {
                const files = e.target.files;
                if (files.length === 0) return;
                
                previewContainer.innerHTML = '';
                
                for (let i = 0; i < files.length; i++) {
                    const file = files[i];
                    const reader = new FileReader();
                    
                    reader.onload = function(e) {
                        const item = document.createElement('div');
                        item.className = 'media-preview-item';
                        
                        if (file.type.startsWith('image/')) {
                            item.innerHTML = `
                                <img src="${e.target.result}" alt="${file.name}">
                                <div class="preview-remove" data-index="${i}">×</div>
                            `;
                        } else if (file.type.startsWith('video/')) {
                            item.innerHTML = `
                                <video src="${e.target.result}" alt="${file.name}" controls muted></video>
                                <div class="preview-remove" data-index="${i}">×</div>
                            `;
                        }
                        
                        previewContainer.appendChild(item);
                    };
                    
                    reader.readAsDataURL(file);
                }
            });
            
            previewContainer.addEventListener('click', function(e) {
                if (e.target.classList.contains('preview-remove')) {
                    const index = parseInt(e.target.dataset.index);
                    const dt = new DataTransfer();
                    const files = Array.from(fileInput.files);
                    files.splice(index, 1);
                    files.forEach(file => dt.items.add(file));
                    fileInput.files = dt.files;
                    e.target.parentElement.remove();
                }
            });
        });
    </script>
</body>
</html>